const Express = require("express");
const RecordServer = require("../../servers/RecordInfo");
const ResponseHelper = require("../ResponseHelper");
const router = Express.Router();
const fs = require("fs");
const { createReadStream, createWriteStream } = require("fs");
const fileUrl = require("../../tools/fileUrl");
const os = require("os");
//type imgs videos both
router.post("/", async (req, res, next) => {
  try {
    const recordInfo = await RecordServer.getByIdAndPatient(req.body.id);
    const type = req.body.type;
    const name = getName(recordInfo);
    const imgOrigin = fileUrl.uploadStaticPath;
    const videoOrign = fileUrl.videoStaticPath;
    if (type === "imgs") {
      const reportimg = JSON.parse(recordInfo.reportimg);
      if (reportimg.length > 0) {
        reportimg.forEach((item) => {
          const urlArrs = item.url.split("/");
          const urlArrsLen = urlArrs.length;
          const imgReadUrl =
            os.platform() === "linux"
              ? `${imgOrigin}/${urlArrs[urlArrsLen - 3]}/${
                  urlArrs[urlArrsLen - 2]
                }/${urlArrs[urlArrsLen - 1]}`
              : `${imgOrigin}\\${urlArrs[urlArrsLen - 3]}\\${
                  urlArrs[urlArrsLen - 2]
                }\\${urlArrs[urlArrsLen - 1]}`;
        //   console.log("img origin addr", imgReadUrl);
        });
      } else {
        ResponseHelper.sendData({ msg: "ok" }, res);
      }
    } else if (type === "videos") {
      const videos = JSON.parse(recordInfo.videos);
      ResponseHelper.sendData("写入完成！", res);
    } else if (type === "both") {
      const reportimg = JSON.parse(recordInfo.reportimg);
      const videos = JSON.parse(recordInfo.videos);
      ResponseHelper.sendData("写入完成！", res);
    }
  } catch (err) {
    ResponseHelper.sendData(err, res);
  }
});

/**
 * 文件读写
 * @param {*} originPath 原始地址
 * @param {*} targetPath 目标
 * @returns
 */
function readAndWriteFile(originPath, targetPath) {
  return new Promise((resolve, reject) => {
    const rs = createReadStream(originPath);
    const ws = createWriteStream(targetPath);
    rs.on("data", (chunk) => {
      ws.write(chunk);
    });
    rs.on("end", (chunk) => {
      ws.end(chunk);
      resolve("Write end");
    });
  });
}

function getName(record) {
  const typeInfo = {
    腹部: "ABD",
    小器官: "SMP",
    血管: "VAS",
    泌尿: "URO",
  };
  const pos = record.pos;
  let fileName;
  if (pos && typeInfo[pos]) {
    fileName = typeInfo[pos];
  } else {
    fileName = "XXX";
  }
  return `${record.name}CO${fileName}-${record.id}`;
}

function getImageName(record, index) {
  try {
    const typeInfo = {
      腹部: "ABD",
      小器官: "SMP",
      血管: "VAS",
      泌尿: "URO",
    };
    const pos = record.pos;
    let fileName;
    if (pos && typeInfo[pos]) {
      fileName = typeInfo[pos];
    } else {
      fileName = "XXX";
    }
    return `${record.id}_${fileName}${index}`;
  } catch (err) {
    console.log(err);
  }
}

module.exports = router;
